package com.ljx.funchat.user.dao;

import com.ljx.funchat.chat.domain.enums.RoomStatusEnum;
import com.ljx.funchat.common.domain.vo.req.CursorPageBaseReq;
import com.ljx.funchat.common.domain.vo.resp.CursorPageBaseResp;
import com.ljx.funchat.common.utils.CursorUtils;
import com.ljx.funchat.user.domain.entity.UserFriend;
import com.ljx.funchat.user.mapper.UserFriendMapper;
import com.ljx.funchat.user.service.IUserFriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 好友表 服务实现类
 * </p>
 *
 * @author LiJunXi
 * @since 2024-02-14
 */
@Service
public class UserFriendDao extends ServiceImpl<UserFriendMapper, UserFriend> {

    public CursorPageBaseResp<UserFriend> getFriendPage(Long uid, CursorPageBaseReq request) {
        return CursorUtils.getCursorPageByMysql(this, request, wrapper -> {
            wrapper.eq(UserFriend::getUid, uid);
        }, UserFriend::getId);
    }

    public boolean countIsFriend(Long uid, Long targetId) {
        // 不能添加自己为好友
        if (uid.equals(targetId)){
            return true;
        }
        Integer count = lambdaQuery().eq(UserFriend::getUid, uid)
                .eq(UserFriend::getFriendUid, targetId)
                .or()
                .eq(UserFriend::getUid, targetId)
                .eq(UserFriend::getFriendUid, uid)
                .count();
        return count > 0;
    }

    public List<UserFriend> getFriendByIds(Long uid, Long targetId) {
        return lambdaQuery().eq(UserFriend::getUid, uid)
                .eq(UserFriend::getFriendUid, targetId)
                .or()
                .eq(UserFriend::getUid, targetId)
                .eq(UserFriend::getFriendUid, uid)
                .list();
    }

    public void deleteByIds(Long uid, Long targetId) {
        lambdaUpdate().set(UserFriend::getDeleteStatus, RoomStatusEnum.ERROR.getStatus())
                .eq(UserFriend::getUid, uid)
                .eq(UserFriend::getFriendUid, targetId)
                .or()
                .eq(UserFriend::getUid, targetId)
                .eq(UserFriend::getFriendUid, uid)
                .update();
    }
}
